package com.bio.service.product.impl;

import java.io.Serializable;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.bio.dao.product.ProductDao;
import com.bio.entity.attachemnt.Attachment;
import com.bio.entity.product.Product;
import com.bio.exception.OperationException;
import com.bio.service.attachment.AttachmentService;
import com.bio.service.impl.AbstractService;
import com.bio.service.product.ProductService;
import com.bio.utils.Environment;

public class ProductServiceImpl extends AbstractService<Product, ProductDao> implements ProductService{

	public ProductServiceImpl(ProductDao dao) {
		super(dao);
	}

    private AttachmentService attachmentService;

    @Override
	public Product save(Product product) throws OperationException {
		Long userId = Environment.Session.getUserId();
		String userName = Environment.Session.getUserName();
		List<Attachment> attachments = product.getAttachments();
		if(null != product){
			product.setPublisherId(userId);
			product.setPublisherName(userName);
			
			String jsonString = attachmentService.batchProcess(attachments, product.getAttachmentsInfo(), product.getToDeletePics());
			product.setAttachmentsInfo(jsonString);
			product = super.save(product);
		}
		return product;
	}

	@Override
	public Product get(Serializable id) {
		Product product = super.get(id);
		if(null != product && StringUtils.isNotEmpty(product.getAttachmentsInfo())){
			JSONArray jArray = JSONArray.fromObject(product.getAttachmentsInfo());
			product.setAttachJSON(JSONArray.toList(jArray, JSONObject.class));
		}
		return product;
	}
    
	public AttachmentService getAttachmentService() {
		return attachmentService;
	}

	public void setAttachmentService(AttachmentService attachmentService) {
		this.attachmentService = attachmentService;
	}
}
